<template>
  <div class="login-container">
    <!-- 返回用户登录按钮 -->
    <div class="back-button">
      <el-button
        type="info"
        plain
        :icon="ArrowLeft"
        @click="goToUserLogin"
      >
        返回用户登录
      </el-button>
    </div>
    
    <el-card class="login-card">
      <template #header>
        <div class="card-header">
          <h2>🍔 外卖平台管理后台</h2>
          <p>管理员登录</p>
        </div>
      </template>
      
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="rules"
        label-width="0"
        size="large"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入管理员用户名"
            :prefix-icon="User"
            clearable
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入管理员密码"
            :prefix-icon="Lock"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            style="width: 100%"
            @click="handleLogin"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="footer-tips">
        <el-text type="info" size="small">
          <el-icon><InfoFilled /></el-icon>
          仅限管理员账号登录
        </el-text>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, ArrowLeft, InfoFilled } from '@element-plus/icons-vue'
import { login } from '@/api/auth'

const router = useRouter()
const loginFormRef = ref(null)
const loading = ref(false)

const loginForm = reactive({
  username: '',
  password: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '用户名至少3个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码至少6个字符', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  await loginFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    loading.value = true
    
    try {
      const res = await login({
        username: loginForm.username,
        password: loginForm.password
      })
      
      console.log('登录响应数据：', res)
      
      // 后端返回格式：{ code: 200, data: { user: {...}, token: '...' }, message: '...' }
      const userData = res.data.user || res.data
      const token = res.data.token
      
      // 检查是否是管理员
      if (userData.role !== 'admin') {
        ElMessage.error('您不是管理员，无法登录管理后台')
        return
      }
      
      // 保存登录信息（使用 sessionStorage，关闭浏览器标签页后自动清除）
      sessionStorage.setItem('admin_token', token)
      sessionStorage.setItem('user_role', userData.role)
      sessionStorage.setItem('admin_user', JSON.stringify(userData))
      
      ElMessage.success('登录成功')
      
      // 跳转到首页
      router.push('/')
    } catch (error) {
      console.error('登录失败：', error)
      ElMessage.error(error.message || '登录失败，请检查用户名和密码')
    } finally {
      loading.value = false
    }
  })
}

// 返回用户登录页面
const goToUserLogin = () => {
  // 开发环境跳转到 Uni-app 登录页（端口5173）
  // 生产环境跳转到主域名登录页
  const userLoginUrl = process.env.NODE_ENV === 'production'
    ? '/'  // 生产环境：主站登录页
    : 'http://localhost:5173/'  // 开发环境：Uni-app 端口
  
  window.location.href = userLoginUrl
}
</script>

<style scoped>
.login-container {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.back-button {
  position: absolute;
  top: 30px;
  left: 30px;
  z-index: 10;
}

.login-card {
  width: 450px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  border-radius: 8px;
}

.card-header {
  text-align: center;
  padding: 10px 0;
}

.card-header h2 {
  margin: 0 0 10px 0;
  font-size: 26px;
  color: #303133;
  font-weight: 600;
}

.card-header p {
  margin: 0;
  font-size: 14px;
  color: #909399;
}

.footer-tips {
  margin-top: 20px;
  text-align: center;
  padding: 12px;
  background-color: #f4f4f5;
  border-radius: 4px;
}

.footer-tips :deep(.el-text) {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.footer-tips :deep(.el-icon) {
  font-size: 14px;
}
</style>
